package com.sl.mes.app.util;

import com.sl.mes.db.vo.OrgGroup;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@SuppressWarnings("all")
public class HttpUtil {

	private static DefaultHttpClient client;

	public static DefaultHttpClient getHttpClient() {

		if (client == null) {

			client = new DefaultHttpClient();

			enableSSL(client);

		}

		return client;
	}

	/**
	 * 访问https的网站
	 * 
	 * @param httpclient
	 */
	private static void enableSSL(DefaultHttpClient httpclient) {

		// 调用ssl
		try {
			SSLContext sslcontext = SSLContext.getInstance("TLS");

			sslcontext.init(null, new TrustManager[] { truseAllManager }, null);

			SSLSocketFactory sf = new SSLSocketFactory(sslcontext);

			sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

			Scheme https = new Scheme("https", sf, 443);

			httpclient.getConnectionManager().getSchemeRegistry().register(https);

		} catch (Exception e) {

			e.printStackTrace();

		}
	}

	/**
	 * 重写验证方法，取消检测ssl
	 */
	private static TrustManager truseAllManager = new X509TrustManager() {

		public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException {
			// TODO Auto-generated method stub

		}

		public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) throws CertificateException {
			// TODO Auto-generated method stub

		}

		public java.security.cert.X509Certificate[] getAcceptedIssuers() {
			// TODO Auto-generated method stub
			return null;
		}

	};

	/**
	 * @param url
	 * @return
	 */
	public static String sendDataByGet(String url) {

		// 创建HttpClient实例
		if (client == null) {

			client = new DefaultHttpClient();

			enableSSL(client);

		}

		// 创建Get方法实例
		HttpGet httpsgets = new HttpGet(url);

		String strRep = "";

		try {

			HttpResponse response = client.execute(httpsgets);

			HttpEntity entity = response.getEntity();

			if (entity != null) {

				strRep = EntityUtils.toString(response.getEntity());

				// Do not need the rest
				httpsgets.abort();
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return strRep;
	}

	/**
	 * HTTP Client Object,used HttpClient Class before(version 3.x),but now the HttpClient is an interface
	 */

	public static String sendXMLDataByGet(String url, String xml) {

		// 创建HttpClient实例
		if (client == null) {

			client = new DefaultHttpClient();

			enableSSL(client);
		}

		StringBuilder urlString = new StringBuilder();

		urlString.append(url);

		urlString.append("?");

		System.out.println("getUTF8XMLString(xml):" + getUTF8XMLString(xml));

		try {
			urlString.append(URLEncoder.encode(getUTF8XMLString(xml), "UTF-8"));
		} catch (UnsupportedEncodingException e1) {
			// TODO 自动生成的 catch 块
			e1.printStackTrace();
		}
		String urlReq = urlString.toString();
		// 创建Get方法实例
		HttpGet httpsgets = new HttpGet(urlReq);

		String strRep = "";
		try {
			HttpResponse response = client.execute(httpsgets);
			HttpEntity entity = response.getEntity();

			if (entity != null) {
				strRep = EntityUtils.toString(response.getEntity());
				// Do not need the rest
				httpsgets.abort();
			}
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return strRep;
	}

	/**
	 * Send a XML-Formed string to HTTP Server by post method
	 * 
	 * @param url
	 *            the request URL string
	 * @param xmlData
	 *            XML-Formed string ,will not check whether this string is XML-Formed or not
	 * @return the HTTP response status code ,like 200 represents OK,404 not found
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	public static String sendXMLDataByPost(String url, String xmlData) throws ClientProtocolException, IOException {

		if (client == null) {
			client = new DefaultHttpClient();
			enableSSL(client);
		}

		client.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
		client.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
		client.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
		client.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);

		// System.out.println(HTTP.UTF_8);
		// Send data by post method in HTTP protocol,use HttpPost instead of
		// PostMethod which was occurred in former version
		// System.out.println(url);
		HttpPost post = new HttpPost(url);
		post.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
		post.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);
		post.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);
		post.getParams().setParameter(HTTP.DEFAULT_PROTOCOL_CHARSET, HTTP.UTF_8);

		// Construct a string entity
		StringEntity entity = new StringEntity(getUTF8XMLString(xmlData), "UTF-8");
		entity.setContentType("text/xml;charset=UTF-8");
		entity.setContentEncoding("UTF-8");

		// Set XML entity
		post.setEntity(entity);

		// Set content type of request header
		post.setHeader("Content-Type", "text/xml;charset=UTF-8");

		// Execute request and get the response
		HttpResponse response = client.execute(post);
		HttpEntity entityRep = response.getEntity();
		String strrep = "";
		if (entityRep != null) {
			strrep = EntityUtils.toString(response.getEntity());
			// Do not need the rest
			post.abort();
		}

		// Response Header - StatusLine - status code
		// statusCode = response.getStatusLine().getStatusCode();
		return strrep;
	}

	/**
	 * Get XML String of utf-8
	 * 
	 * @return XML-Formed string
	 */
	public static String getUTF8XMLString(String xml) {
		// A StringBuffer Object
		StringBuffer sb = new StringBuffer();
		sb.append(xml);
		String xmString = "";
		try {
			xmString = new String(sb.toString().getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// return to String Formed
		return xmString.toString();
	}

	/**
	 * 将一个 JavaBean 对象转化为一个 Map
	 * 
	 * @param bean
	 *            要转化的JavaBean 对象
	 * @return 转化出来的 Map 对象
	 * @throws IntrospectionException
	 *             如果分析类属性失败
	 * @throws IllegalAccessException
	 *             如果实例化 JavaBean 失败
	 * @throws InvocationTargetException
	 *             如果调用属性的 setter 方法失败
	 */
	@SuppressWarnings("rawtypes")
	public static Map<String, Object> convertBean(Object bean) throws IntrospectionException, IllegalAccessException, InvocationTargetException {
		Class type = bean.getClass();
		Map<String, Object> returnMap = new HashMap<String, Object>();
		BeanInfo beanInfo = Introspector.getBeanInfo(type);

		PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
		for (int i = 0; i < propertyDescriptors.length; i++) {
			PropertyDescriptor descriptor = propertyDescriptors[i];
			String propertyName = descriptor.getName();
			if (!propertyName.equals("class")) {
				Method readMethod = descriptor.getReadMethod();
				Object result = readMethod.invoke(bean, new Object[0]);
				if (result != null) {
					returnMap.put(propertyName, result);
				} else {
					returnMap.put(propertyName, "");
				}
			}
		}
		return returnMap;
	}

	/**
	 * 获取一定长度的随机字符串
	 * 
	 * @param length
	 *            指定字符串长度
	 * @return 一定长度的字符串
	 */
	public static String getNonce_str(int length) {
		String base = "abcdefghijklmnopqrstuvwxyz0123456789";
		Random random = new Random();
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int number = random.nextInt(base.length());
			sb.append(base.charAt(number));
		}
		return sb.toString();
	}

	/**
	 * 调用移动服务的信息发送请求
	 *
	 * @throws Exception
	 */
	public static String exeApplyJsonObjectRequest(String strUrl,Map<String, Object> paramsMap) throws Exception {

		// 第一步：API服务地址
		HttpPost httpPost = new HttpPost(strUrl);

		//第二步：
		//map转json对象
		net.sf.json.JSONObject paramsJson=net.sf.json.JSONObject.fromObject(paramsMap);
		StringEntity se = new StringEntity(paramsJson.toString(), "utf-8");
		//设置为json格式
		se.setContentType("application/json");
		httpPost.setHeader("Content-Type", "application/json");
		httpPost.setHeader("cookiets", "1640068633741");
		httpPost.setEntity(se); // post方法中，加入json数据


		// 第三步：发送http post请求，并得到相应结果
		String result = "";
		HttpResponse response = HttpUtil.getHttpClient().execute(httpPost);
		if (response != null) {
			HttpEntity resEntity = response.getEntity();
			if (resEntity != null) {
				result = EntityUtils.toString(resEntity, "UTF-8");
				System.out.println(result);
			}
		}
		return result;
	}
}
